<?php
namespace app\api\controller;

use app\common\controller\Api;

class Ocr extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    // 你的 APPID AK SK
    const APP_ID = 57555162;
    const API_KEY = 'jrMQFSrhv8kE3ZL8PM3GpNRi';
    const SECRET_KEY = 'jtI9ZGehUrmAenDj0kYKKexzS7lLN56r';

    // 识别文字
    public function scanningToWord()
    {
        require_once 'extend/ocr/AipOcr.php';
        $client = new \AipOcr(APP_ID, API_KEY, SECRET_KEY);
        $image = file_get_contents('example.jpg');

        // 调用通用文字识别, 图片参数为本地图片
        $client->basicGeneral($image);

        // 如果有可选参数
        $options = array();
        $options["language_type"] = "CHN_ENG";
        $options["detect_direction"] = "true";
        $options["detect_language"] = "true";
        $options["probability"] = "true";

        // 带参数调用通用文字识别, 图片参数为本地图片
        $client->basicGeneral($image, $options);
        $url = "https//www.x.com/sample.jpg";

        // 调用通用文字识别, 图片参数为远程url图片
        $client->basicGeneralUrl($url);

        // 如果有可选参数
        $options = array();
        $options["language_type"] = "CHN_ENG";
        $options["detect_direction"] = "true";
        $options["detect_language"] = "true";
        $options["probability"] = "true";

        // 带参数调用通用文字识别, 图片参数为远程url图片
        $client->basicGeneralUrl($url, $options);
    }

    // 识别图片/PDF格式文档中的表格内容



    public function scanningToExcel()
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token?client_id='.self::API_KEY.'&client_secret='.self::SECRET_KEY.'&grant_type=client_credentials';
        $token = self::httpPost($url);
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/table?access_token=' . $token['access_token'];
        $img = file_get_contents('http://demo.fastadmin.com/uploads/20240321/9482a075bbcd1b5fbc6e6f1e47e34580.jpg');
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img,
            'return_excel' => 'true', //是否输出表格内容
        );
        $res = self::request_post($url, $bodys);

        $res = json_decode($res,true);
        $excel_url_base64 = $res['excel_file'];
        // 使用base64_decode解码Base64字符串
        $excel_url = base64_decode($excel_url_base64);
        // 指定要创建的文件名
        $path = 'excel/'.date('Y-m-d');
        if (!is_dir($path)) {
            if (!mkdir($path,0775, true)) {
                $this->error('文件创建失败');
            }
        }
        $file = 'excel/'.date('Y-m-d').'/'.time().'.xlsx';
        // 将数据写入文件
        $result = file_put_contents($file, $excel_url);
        if ($result !== false) {
            $this->success('文件保存成功');
        } else {
            $this->error('文件保存失败');
        }


        $this->success('请求成功',$excel_url);



        // 创建PHPExcel对象
        $objPHPExcel = new PHPExcel();
        $sheet = $objPHPExcel->getActiveSheet();

        // 填充表头
        $sheet->setCellValue('A1', '文字内容');
        $sheet->setCellValue('B1', '置信度');
        $sheet->setCellValue('C1', '区域坐标');

        // 填充OCR识别的文字数据
        if ($ocrResult['words_result_num'] > 0) {
            $row = 2;
            foreach ($ocrResult['words_result'] as $word) {
                $sheet->setCellValue('A' . $row, $word['words']);
                $sheet->setCellValue('B' . $row, $word['probability']);
                $sheet->setCellValue('C' . $row, implode(',', $word['location']));
                $row++;
            }
        }

// 设置Excel格式
        $sheet->setTitle('OCR结果');

// 设置输出的Excel文件
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="ocr_result.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        echo $res;

    }


    public function getAccessToken() {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id=".self::API_KEY."&client_secret=".self::SECRET_KEY."&grant_type=client_credentials",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',


            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json'
            ),

        ));
        $response = curl_exec($curl);
        dump($response);exit;
        curl_close($curl);
        return $response;
    }


    private function httpPost($url, $data = array())
    {
        $data_string = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//取消证书验证

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($data_string))
        );

        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);

        $output = json_decode($output, true);


        return $output;
    }

    /**
     * 发起http post请求(REST API), 并获取REST请求的结果
     * @param string $url
     * @param string $param
     * @return - http response body if succeeds, else false.
     */
    private function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }
}